import config from '@/config'
import store from '@/store/store'
import {
	toast,
	showConfirm
} from '@/common/common'
const errorCode = {
	'401': '认证失败，无法访问系统资源',
	'403': '当前操作没有权限',
	'404': '访问资源不存在',
	'default': '系统未知错误，请反馈给管理员'
}
let isShow = false
let requestNum = 0;
//#ifdef H5
const BASE_URL = "baseUrlTest";
//#endif
//#ifdef MP-WEIXIN
const BASE_URL = config.baseUrl;
//#endif
const request = data => {
	data.header = data.header || {}
	if (!data.noToken) {
		data.header['Authorization'] = 'Bearer ' + store.state.token
	}

	// get请求映射params参数
	if (data.params) {
		let url = data.url + '?'
		for (const propName of Object.keys(data.params)) {
			const value = data.params[propName]
			var part = encodeURIComponent(propName) + '='
			if (value !== null && typeof value !== 'undefined') {
				if (typeof value === 'object') {
					for (const key of Object.keys(value)) {
						if (value[key] !== null && typeof value[key] !== 'undefined') {
							let params = propName + '[' + key + ']'
							let subPart = encodeURIComponent(params) + '='
							url += subPart + encodeURIComponent(value[key]) + '&'
						}
					}
				} else {
					url += part + encodeURIComponent(value) + '&'
				}
			}
		}
		url = url.slice(0, -1)

		data.url = url

	}

	return new Promise((resolve, reject) => {


		uni.request({
				method: data.method || 'get',
				url: BASE_URL + data.url,
				data: data.param,
				header: data.header,
				dataType: 'json',
			})
			.then(response => {
				let [error, res] = response
				uni.stopPullDownRefresh();
				if (error) {
					throw new Error('后端接口连接异常')
					return
				}

				const msg = errorCode[code] || res.data.msg || errorCode['default']
				const code = res.data.code || 200
				if (code == '401') {
					uni.clearStorageSync()
					uni.reLaunch({
						url: '/pages//mine/index'
					})
				
					throw new Error('无效的会话，或者会话已过期，请重新登录')

				} else if (code === 500) {
					throw new Error(msg)
				} else if (code !== 200) {
					throw new Error(msg)
				}

				resolve(res.data)
			})
			.catch(error => {
				console.log('报错信息', error);

				uni.stopPullDownRefresh();
				let {
					message
				} = error
				if (message === 'Network Error') {
					message = '后端接口连接异常'
				} else if (message.includes('timeout')) {
					message = '系统接口请求超时'
				} else if (message.includes('Request failed with status code')) {
					message = '系统接口' + message.substr(message.length - 3) + '异常'
				}

				reject(message)
			})
	})
}
const upload = data => {
	let header = {}
	header['Authorization'] = 'Bearer ' + store.state.token

	return new Promise((resolve, reject) => {

		uni.uploadFile({
			url: BASE_URL + data.url,

			//	filePath: data.data.path,
			files: data.data,
			name: 'file',

			header: header,
			success: response => {

				uni.stopPullDownRefresh()
				// uni.hideLoading()
				var res = JSON.parse(response.data)

				if (res.code === 200) {
					resolve(res)
				} else if (res.code === 401) {
					showConfirm('登录状态已过期，您可以继续留在该页面，或者重新登录?')
						.then(res => {
							if (res.confirm) {
								store.dispatch('LogOut')
									.then(res => {
										uni.reLaunch({
											url: '/pages/mine/index'
										})
									})
							}
						})
					reject('无效的会话，或者会话已过期，请重新登录。')
				} else if (res.code === 500) {
					toast(res.msg)
					reject('500')
				}
			},
			fail: error => {

				uni.stopPullDownRefresh()
				// uni.hideLoading()
				toast(error.errMsg)
				reject(error.errMsg)
			}
		})
	})
}
module.exports = {
	request,
	upload
}